import { treeOrganization } from '@/services/api/api-admin-organization';
import { CloseOutlined, FolderOutlined, HomeOutlined } from '@ant-design/icons';
import { Button, Space, Tree } from 'antd';

import ProCard from '@ant-design/pro-card';
import { DataNode } from 'antd/lib/tree';
import React, { useEffect, useState } from 'react';
import AddOrganization from './AddOrganization';
import EditOrganization from './EditOrganization';

interface TreeOrganizationProps {
  onSelect: (info: any) => void;
  onRefurbish: () => void;
}
const TreeOrganization: React.FC<TreeOrganizationProps> = ({ onSelect, onRefurbish }) => {
  /**
   * 初始化树形数据
   */
  const [dataTree, setDataTreeState] = useState<DataNode[]>();

  /**
   * 树形列表选择数据
   */
  const [selectNode, setSelectNodeState] = useState<any>();

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          title: val.name,
          key: val.id,
          item: val,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
          icon:
            val.state === 1 ? (
              val.isFolder === 0 ? (
                <HomeOutlined />
              ) : (
                <FolderOutlined />
              )
            ) : (
              <CloseOutlined />
            ),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载权限详情
   * @param key
   */
  const loadOrganizationData = async () => {
    try {
      const response = await treeOrganization();
      if (response.code === 0) {
        const treeData = new Array<DataNode>();
        treeData.push({
          title: '五媒协同',
          key: '0',
          item: { id: '0', name: '五媒协同' },
          children: readyTreeData(response.data),
        });
        setDataTreeState(treeData);
      }
    } catch (error) {}
  };

  /**
   * 恢复默认
   */
  useEffect(() => {
    loadOrganizationData();
  }, []);

  return (
    <ProCard
      title="组织树"
      extra={
        selectNode?.selected && (
          <Space wrap>
            {selectNode?.node?.pos.length > 4 && (
              <EditOrganization
                data={selectNode.node.item}
                onRefurbish={() => {
                  loadOrganizationData();
                  onRefurbish();
                }}
              />
            )}
            {selectNode?.node?.pos.length > 2 && (
              <AddOrganization
                parent={selectNode.node.item}
                onRefurbish={() => {
                  loadOrganizationData();
                  onRefurbish();
                }}
              />
            )}
            {selectNode?.node?.item?.parentId === '0' && <Button type="primary">业务属性（待定）</Button>}
            {/* <Button
              type="primary"
              danger
              disabled={selectNode?.node?.pos.length <= 4}
              onClick={() => {
                Modal.confirm({
                  title: '是否要删除该组织',
                  icon: <ExclamationCircleOutlined />,
                  okText: '是',
                  okType: 'danger',
                  cancelText: '否',
                  async onOk() {
                    try {
                      const response = await deleteOrganization({ id: selectNode?.node?.key });
                      if (response.code === 0) {
                        message.success('提交成功');
                        loadOrganizationData();
                        onSelect({});
                        setSelectNodeState({});
                        onRefurbish();
                      }
                    } catch (error) {
                      message.success('提交失败');
                    }
                  },
                  onCancel() {},
                });
              }}
            >
              删除
            </Button> */}
          </Space>
        )
      }
    >
      {dataTree && dataTree.length ? (
        <Tree
          defaultExpandedKeys={['0']}
          height={800}
          showLine={{ showLeafIcon: false }}
          showIcon={true}
          treeData={dataTree}
          onSelect={(selectedKeys: React.Key[], info: any) => {
            console.log('=========', info);
            onSelect(info);
            setSelectNodeState(info);
          }}
        />
      ) : (
        '暂无数据'
      )}
    </ProCard>
  );
};
export default TreeOrganization;
